package day03.window;

import beans.SensorReading;
import custom.MyCountAggregateFunction;
import custom.MyTimestampExtractor;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.*;
import org.apache.flink.streaming.api.windowing.time.Time;

/**
 * Flink 流处理 API -  EventTime 在 window 中的使用
 *
 * @author lvbingbing
 * @date 2022-01-01 13:05
 */
public class FlinkWindow05 {
    public static void main(String[] args) throws Exception {
        // 1、创建 FlinkWindow00 对象，有参构造会初始化 env，并从socket文本流中读取数据
        int parallelism = 1;
        FlinkWindow00 flinkWindow = new FlinkWindow00(parallelism);
        // 2、获取可执行环境
        StreamExecutionEnvironment env = flinkWindow.getEnv();
        // 3、设置事件特性为 EventTime
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
        env.getConfig().setAutoWatermarkInterval(100);
        // 4、学习事件时间窗口
        studyEventTimeWindow(flinkWindow.getSingleOutputStreamOperator());
        // 5、触发程序执行
        env.execute();
    }

    /**
     * 学习事件时间窗口
     * <p>
     * 1、滚动窗口(Tumbling Window)
     * 2、滑动窗口(Sliding Window)
     * 3、会话窗口(Session Window)
     * <p>
     * 已指定时间特性为：事件时间
     *
     * @param sensorReadingStream <br>
     * @see StreamExecutionEnvironment#DEFAULT_TIME_CHARACTERISTIC
     */
    public static void studyEventTimeWindow(SingleOutputStreamOperator<SensorReading> sensorReadingStream) {
        // 1、Tumbling Window
        studyEventTimeTumblingWindow(sensorReadingStream);
        // 2、Sliding Window
        studyEventTimeSlidingWindow(sensorReadingStream);
        // 3、Session Window
        studyEventTimeSessionWindow(sensorReadingStream);
    }

    /**
     * 事件时间滚动窗口
     *
     * @param sensorReadingStream <br>
     * @see TimeCharacteristic
     */
    private static void studyEventTimeTumblingWindow(SingleOutputStreamOperator<SensorReading> sensorReadingStream) {
        // 方式一：使用 timeWindow() 设置事件时间滚动窗口
        // 1、设置时间戳与水位线
        SingleOutputStreamOperator<SensorReading> dataStream = sensorReadingStream.assignTimestampsAndWatermarks(new MyTimestampExtractor(Time.seconds(2)));
        // 2、设置事件时间滚动窗口，并对数据做聚合
        SingleOutputStreamOperator<SensorReading> resStream = dataStream.keyBy("id")
                .timeWindow(Time.seconds(15))
                .minBy("temperature");
        resStream.print("使用timeWindow()设置事件时间滚动窗口");
        // 方式二：使用 window() 设置事件时间滚动窗口
        SingleOutputStreamOperator<Integer> tumblingEventTimeWindowDs = dataStream.keyBy("id")
                .window(TumblingEventTimeWindows.of(Time.seconds(15)))
                .aggregate(new MyCountAggregateFunction());
        tumblingEventTimeWindowDs.print("事件时间滚动窗口");
    }

    /**
     * 事件时间滑动窗口
     *
     * @param sensorReadingStream <br>
     */
    private static void studyEventTimeSlidingWindow(SingleOutputStreamOperator<SensorReading> sensorReadingStream) {
        // 方式一：使用 timeWindow() 设置事件时间滑动窗口
        // 1、设置时间戳与水位线
        SingleOutputStreamOperator<SensorReading> dataStream = sensorReadingStream.assignTimestampsAndWatermarks(new MyTimestampExtractor(Time.seconds(2)));
        // 2、设置事件时间滑动窗口，并对数据做聚合
        SingleOutputStreamOperator<Integer> resStream = dataStream.keyBy("id")
                .timeWindow(Time.seconds(15), Time.seconds(5))
                .aggregate(new MyCountAggregateFunction());
        resStream.print("使用 timeWindow() 设置事件时间滑动窗口");
        // 方式二：使用 window() 设置事件时间滑动窗口
        SingleOutputStreamOperator<Integer> slidingEventTimeWindowDs = dataStream.keyBy("id")
                .window(SlidingEventTimeWindows.of(Time.seconds(15), Time.seconds(15)))
                .aggregate(new MyCountAggregateFunction());
        slidingEventTimeWindowDs.print("事件时间滑动窗口");
    }

    /**
     * 事件时间会话窗口
     *
     * @param sensorReadingStream <br>
     */
    private static void studyEventTimeSessionWindow(SingleOutputStreamOperator<SensorReading> sensorReadingStream) {
        // 使用 window() 设置时间时间会话窗口
        SingleOutputStreamOperator<SensorReading> dataStream = sensorReadingStream.assignTimestampsAndWatermarks(new MyTimestampExtractor(Time.seconds(2)));
        SingleOutputStreamOperator<Integer> eventTimeSessionWindowsDs = dataStream.keyBy("id")
                .window(EventTimeSessionWindows.withGap(Time.seconds(15)))
                .aggregate(new MyCountAggregateFunction());
        eventTimeSessionWindowsDs.print("事件时间会话窗口");
    }
}
